package org.groupg.project.configmanager.repository;


import jakarta.persistence.EntityManager;
import org.groupg.project.configmanager.model.DatabaseConfig;
import org.groupg.project.configmanager.util.JPAUtil;

import java.util.Optional;

public class DatabaseConfigRepository extends BaseRepository<DatabaseConfig, Integer> {

    public DatabaseConfigRepository() {
        super(DatabaseConfig.class);
    }

    @Override
    protected boolean isNew(DatabaseConfig entity) {
        return entity.getId() == null;
    }

    public Optional<DatabaseConfig> findByName(String name) {
        return JPAUtil.executeInTransaction(entityManager -> {
            String jpql = "SELECT d FROM DatabaseConfig d WHERE d.name = :name";
            try {
                DatabaseConfig config = entityManager.createQuery(jpql, DatabaseConfig.class)
                        .setParameter("name", name)
                        .getSingleResult();
                return Optional.of(config);
            } catch (Exception e) {
                return Optional.empty();
            }
        });
    }
}